package com.erp.dao;

import com.erp.bean.User;
import com.erp.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lqa
 * @Date 2022-04-20 14:25:33
 */
public class UserDao {

    JDBCUtils jdbcUtils = new JDBCUtils();

    /* *
     * @author lqa
     * @name 查询用户列表
     * @time 16:01 2022/4/20
     * @param page:
     * @param size:
     * @return java.util.List<com.erp.bean.User>
     **/
    public List<User> listQuery(int page, int size) {
        List<User> list = new ArrayList<>();

        try {
            PreparedStatement pstm = null;
            ResultSet rs = null;
            Connection connection = jdbcUtils.getConnection();
            if (connection != null) {
                String sql = "select * from user limit ?,?";
                Object[] params = {page, size};
                rs = jdbcUtils.execute(connection, sql, params, rs, pstm);
                while (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setSex(rs.getString("sex"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                    list.add(user);
                }
                jdbcUtils.closeResource(connection, pstm, rs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /* *
     * @author lqa
     * @name 根据用户名查找用户
     * @time 16:02 2022/4/20
     * @param username:
     * @return com.erp.bean.User
     **/
    public User getUserByUsername(String username) {
        User user = null;

        try {
            PreparedStatement pstm = null;
            ResultSet rs = null;
            Connection connection = jdbcUtils.getConnection();
            if (connection != null) {
                String sql = "select * from user where username = ?";
                Object[] params = {username};
                rs = jdbcUtils.execute(connection, sql, params, rs, pstm);
                while (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setSex(rs.getString("sex"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                }
                jdbcUtils.closeResource(connection, pstm, rs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }

}